const ajax = require('axios')
// 进行xlsx文件的读取
const xlsx = require("node-xlsx"); //核心模块
// const fs = require('fs'); 
const city = xlsx.parse(__dirname + "/test.xlsx")[0].data; //文件名 node-xlsx.xlsx
let cityList = handleData(city)



// 天气功能的接口
module.exports = (router) => {
    router.get('/cityList', function(req, res){
        // 返回数据格式 [{prov:河北省；[{city:秦皇岛市；district:[{name:海港区；code:130302},{name:山海关；code:130303}]],[city:唐山市；……]},{prov:……}]
        res.send({code:0,data:cityList})
    })
    router.get('/weather', async function(req, res){
        let {location} = req.query
        let r = await Axios(`http://api.map.baidu.com/weather/v1/?district_id=${location}&data_type=all&ak=uyv7xt0s5HQR3BMp56Za0WM2RzGZce3R`)
        res.send({code:0,data:r})
    })
}

// 请求函数
function Axios(url,data){
    return new Promise((resolve,reject) => {
        // 请求天气
        let promise = ajax.get(url,data)
        promise.then((res) => {
            // console.log('res',res)
            resolve((res.data))
        }).catch((err) => {
            resolve({code:1,msg:'请求失败',err})
        })
    })
}
// 数据处理函数 将城市数据处理成
//返回数据格式 
//[{prov:河北省；inner:[{city:秦皇岛市；district:[{name:海港区；code:130302},{name:山海关；code:130303}]],[city:唐山市；……]},{prov:……}]
function handleData(data){
    let res = []
    let pro_name = '' // 记录上一个省的名字
    let city_geocode = -1 // 记录上一个市的名字
    let lenth = data.length
    for(let i = 1;i < lenth; i++){
        if(data[i][1] != pro_name){
            //需要新创建一个省
            res.push({prov:data[i][1],inner:[{city:data[i][2],district:[{name:data[i][4],code:data[i][5]}]}]})
            pro_name = data[i][1]
            city_geocode = data[i][3]
        }else if(data[i][3] != city_geocode){
            //需要新创建一个市
            res[res.length - 1].inner.push({city:data[i][2],district:[{name:data[i][4],code:data[i][5]}]})
            city_geocode = data[i][3]
        }else{
            //不需要创建省，也不需要创建市，一个市的不同地区
            let temp = res[res.length - 1].inner
            temp[temp.length - 1].district.push({name:data[i][4],code:data[i][5]})
        }
    }
    return res
}
